"""
用户相关API路由
"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.schemas.user import (
    User, UserCreate, UserUpdate, UserLogin, Token,
    PasswordChange
)
from app.schemas.common import (
    DataResponse, ListResponse, MessageResponse, 
    PaginationParams
)
from app.services.user_service import user_service
from app.api.deps import (
    get_current_user, get_current_admin_user,
    require_permission
)

router = APIRouter()


@router.post("/register", response_model=DataResponse[User], status_code=status.HTTP_201_CREATED)
async def register_user(
    *,
    db: AsyncSession = Depends(get_db),
    user_in: UserCreate
) -> DataResponse[User]:
    """
    用户注册
    """
    user = await user_service.create_user(db, user_create=user_in)
    return DataResponse(
        data=user,
        message="用户注册成功"
    )


@router.post("/login", response_model=DataResponse[Token])
async def login(
    *,
    db: AsyncSession = Depends(get_db),
    login_data: UserLogin
) -> DataResponse[Token]:
    """
    用户登录
    """
    result = await user_service.login(db, login_data=login_data)
    token_data = Token(
        access_token=result["access_token"],
        refresh_token=result["refresh_token"],
        token_type=result["token_type"],
        expires_in=result["expires_in"]
    )
    
    return DataResponse(
        data=token_data,
        message="登录成功"
    )


@router.post("/refresh-token", response_model=DataResponse[Token])
async def refresh_token(
    *,
    db: AsyncSession = Depends(get_db),
    refresh_token: str
) -> DataResponse[Token]:
    """
    刷新访问令牌
    """
    result = await user_service.refresh_token(db, refresh_token=refresh_token)
    token_data = Token(
        access_token=result["access_token"],
        refresh_token=result["refresh_token"],
        token_type=result["token_type"],
        expires_in=result["expires_in"]
    )
    
    return DataResponse(
        data=token_data,
        message="令牌刷新成功"
    )


@router.get("/me", response_model=DataResponse[User])
async def get_current_user_info(
    current_user: User = Depends(get_current_user)
) -> DataResponse[User]:
    """
    获取当前用户信息
    """
    return DataResponse(
        data=current_user,
        message="获取用户信息成功"
    )


@router.put("/me", response_model=DataResponse[User])
async def update_current_user(
    *,
    db: AsyncSession = Depends(get_db),
    user_update: UserUpdate,
    current_user: User = Depends(get_current_user)
) -> DataResponse[User]:
    """
    更新当前用户信息
    """
    updated_user = await user_service.update_user(
        db, user_id=current_user.id, user_update=user_update
    )
    return DataResponse(
        data=updated_user,
        message="用户信息更新成功"
    )


@router.post("/change-password", response_model=MessageResponse)
async def change_password(
    *,
    db: AsyncSession = Depends(get_db),
    password_change: PasswordChange,
    current_user: User = Depends(get_current_user)
) -> MessageResponse:
    """
    修改密码
    """
    if not password_change.passwords_match():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="新密码和确认密码不匹配"
        )
    
    await user_service.change_password(
        db,
        user_id=current_user.id,
        current_password=password_change.current_password,
        new_password=password_change.new_password
    )
    
    return MessageResponse(message="密码修改成功")


@router.get("/", response_model=ListResponse[User])
async def get_users(
    *,
    db: AsyncSession = Depends(get_db),
    pagination: PaginationParams = Depends(),
    current_user: User = Depends(require_permission("user:read"))
) -> ListResponse[User]:
    """
    获取用户列表(需要权限)
    """
    from app.repositories.user import user_repository
    
    users = await user_repository.get_multi(
        db,
        skip=pagination.offset,
        limit=pagination.page_size
    )
    
    total = await user_repository.count(db)
    
    return ListResponse(
        data=users,
        total=total,
        message="获取用户列表成功"
    )


@router.get("/{user_id}", response_model=DataResponse[User])
async def get_user(
    *,
    db: AsyncSession = Depends(get_db),
    user_id: int,
    current_user: User = Depends(require_permission("user:read"))
) -> DataResponse[User]:
    """
    根据ID获取用户(需要权限)
    """
    user = await user_service.get_user_by_id(db, user_id=user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return DataResponse(
        data=user,
        message="获取用户成功"
    )


@router.put("/{user_id}", response_model=DataResponse[User])
async def update_user(
    *,
    db: AsyncSession = Depends(get_db),
    user_id: int,
    user_update: UserUpdate,
    current_user: User = Depends(require_permission("user:update"))
) -> DataResponse[User]:
    """
    更新用户(需要权限)
    """
    updated_user = await user_service.update_user(
        db, user_id=user_id, user_update=user_update
    )
    return DataResponse(
        data=updated_user,
        message="用户更新成功"
    )


@router.delete("/{user_id}", response_model=MessageResponse)
async def delete_user(
    *,
    db: AsyncSession = Depends(get_db),
    user_id: int,
    current_user: User = Depends(require_permission("user:delete"))
) -> MessageResponse:
    """
    删除用户(需要权限)
    """
    await user_service.delete_user(db, user_id=user_id)
    return MessageResponse(message="用户删除成功")


@router.get("/search/", response_model=ListResponse[User])
async def search_users(
    *,
    db: AsyncSession = Depends(get_db),
    keyword: str = Query(..., description="搜索关键词"),
    pagination: PaginationParams = Depends(),
    current_user: User = Depends(require_permission("user:read"))
) -> ListResponse[User]:
    """
    搜索用户(需要权限)
    """
    from app.repositories.user import user_repository
    
    users = await user_repository.search_users(
        db,
        keyword=keyword,
        skip=pagination.offset,
        limit=pagination.page_size
    )
    
    # 获取搜索结果总数(简化实现)
    total = len(users)
    
    return ListResponse(
        data=users,
        total=total,
        message="搜索用户成功"
    )